import json
from django.utils.encoding import force_text
from rest_framework.exceptions import APIException


class MyException(Exception):

    code = 200
    details = None

    def __init__(self, message=None, *args, **kwargs):
        if isinstance(message, (list, dict)):
            message = json.dumps(
                message, default=str, ensure_ascii=False)
        if message and not isinstance(message, str):
            message = str(message)
        if message is not None:
            self.details = message.encode()
        super().__init__(message, *args, **kwargs)



class JsonAPIException(APIException):
    """
    def get_xxx(self, request, *args, **kwargs):
        if xxx:
            raise JsonAPIException('xxx xxx.', 411)
    """

    def __init__(self, code='OK', msg='Success', errors=[], status=400):
        self.code = code
        self.msg = 'Msg'
        if isinstance(msg, str):
            self.msg = msg
        else:
            e = getattr(msg, code, None)
            if e:
                self.msg = e.value
        self.errors = errors
        self.status = status

    def __str__(self):
        return '%s:%s' % (self.code, self.msg)

class ObjectNotFoundAPIException(JsonAPIException):
    def __init__(self, code, msg, errors=[], status=404):
        super().__init__(code, msg, errors, status)

class ParametersErrorAPIException(JsonAPIException):
    def __init__(self, code, msg, errors=[], status=400):
        super().__init__(code, msg, errors, status)

class InternalServerErrorAPIException(JsonAPIException):
    def __init__(self, code, msg, errors=[], status=500):
        super().__init__(code, msg, errors, status)
